#include "widget.h"
#include "ui_widget.h"
#include<QNetworkDatagram>

const QString &SERVER_IP = "127.0.0.1";
const quint16 SERVER_PORT = 9090;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //初始化操作
    socket = new QUdpSocket(this);


    //修改窗口标题，方便区分客户端
    this->setWindowTitle("客户端");

    //通过信号槽处理返回的数据
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processResponse) ;
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取到输入框的内容
    const QString &text = ui->lineEdit->text();

    //构造一个UDP的请求数据
    QNetworkDatagram  requestDatagram(text.toUtf8(),QHostAddress(SERVER_IP),SERVER_PORT);

    //发送请求数据
    socket->writeDatagram(requestDatagram);

    //把发送的请求添加到列表框种
    ui->listWidget->addItem("客户端说："+text );

    //吧输入框的内容清空
    ui->lineEdit->setText(" ");
}

void Widget::processResponse()
{
    //通过这个函数处理收到的响应
    //读取到响应数据
    const QNetworkDatagram&responseDatagram = socket->receiveDatagram();
    QString response = responseDatagram.data();
    //吧响应数据显示到界面上
    ui->listWidget->addItem("服务器说："+response);
}
